package com.yly.doctorapp.ui.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yly.doctorapp.R;
import com.yly.doctorapp.base.BaseActivity;
import com.yly.doctorapp.base.DoctorAppApplication;
import com.yly.doctorapp.bean.ResponsDataBean;
import com.yly.doctorapp.constant.Configution;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChangePhoneActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.v_phone)
    View vPhone;
    @BindView(R.id.edit_phones)
    EditText editPhones;
    @BindView(R.id.v_phones)
    View vPhones;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.v_code)
    View vCode;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    private SPUtils mSputils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_changephone;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSputils = new SPUtils(getApplicationContext());
        editPhone.setText(getIntent().getStringExtra("phone"));
        editPhone.setEnabled(false);
        editPhone.setFocusable(false);
        editPhone.setFocusableInTouchMode(false);
        editPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    vPhone.setBackgroundColor(0xffa0524b);
                    vPhones.setBackgroundColor(0xffcccccc);
                    vCode.setBackgroundColor(0xffcccccc);
                }
            }
        });
        editPhones.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    vPhone.setBackgroundColor(0xffcccccc);
                    vPhones.setBackgroundColor(0xffa0524b);
                    vCode.setBackgroundColor(0xffcccccc);
                }
            }
        });
        editCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    vPhone.setBackgroundColor(0xffcccccc);
                    vPhones.setBackgroundColor(0xffcccccc);
                    vCode.setBackgroundColor(0xffa0524b);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.iv_back, R.id.tv_getcode, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_getcode:
                if (StringUtils.isEmpty(editPhones.getText().toString())){
                    ToastUtils.show(getApplicationContext(), "请输入新手机", 100);
                    return;
                }
                if (editPhones.getText().toString().length() != 11){
                    ToastUtils.show(getApplicationContext(), "请输入正确的新手机", 100);
                    return;
                }
                tvGetcode.setEnabled(false);
                initHttpSendMessage(editPhones.getText().toString());
                break;
            case R.id.tv_sure:
                if (StringUtils.isEmpty(editPhones.getText().toString())){
                    ToastUtils.show(getApplicationContext(), "请输入新手机", 100);
                    return;
                }
                if (editPhones.getText().toString().length() != 11){
                    ToastUtils.show(getApplicationContext(), "请输入正确的新手机", 100);
                    return;
                }
                if (StringUtils.isEmpty(editCode.getText().toString())){
                    ToastUtils.show(getApplicationContext(), "请输入验证码", 100);
                    return;
                }
                if (null != DoctorAppApplication.mUserBean){
                   initChangePhone(DoctorAppApplication.mUserBean.getDoctorid(), editPhone.getText().toString(), editPhones.getText().toString(), editCode.getText().toString());
                }
                break;
        }
    }

    private void initChangePhone(int doctorid, final String telephone, String newTelephone, String verCode) {
        RequestParams params = new RequestParams(Configution.HOST + Configution.CHANGEPHONE);
        params.addBodyParameter("doctorid", doctorid + "");
        params.addBodyParameter("telephone", telephone);
        params.addBodyParameter("newTelephone", newTelephone);
        params.addBodyParameter("verCode", verCode);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResponsDataBean responsDataBean = JSON.parseObject(result, ResponsDataBean.class);
                    if (responsDataBean.getCode().equals("1000")){
                        AppManager.getAppManager().finishAllActivity();
                        mSputils.putString(Configution.USERPHONE, telephone);
                        Intent mIntent = new Intent(ChangePhoneActivity.this, LoginActivity.class);
                        startActivity(mIntent);
                        finish();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.show(getApplicationContext(), "网络连接失败", 100);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    int count = 120;
    private Thread mThread;
    private boolean isRunnig = true;
    private void showCounter() {
        if (null != mThread) {
            mThread.interrupt();
            mThread = null;
        }
        isRunnig = true;
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunnig) {
                    try {
                        Thread.sleep(1000);
                        if (count > 0) {
                            count--;
                            Message message = new Message();
                            message.what = 0;
                            message.arg1 = count;
                            mHandler.sendMessage(message);
                        } else {
                            mHandler.sendEmptyMessage(1);
                            isRunnig = false;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (UnsupportedOperationException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        mThread.start();
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    tvGetcode.setText(String.valueOf(msg.arg1) + "S");
                    break;
                case 1:
                    tvGetcode.setText("获取验证码");
                    tvGetcode.setEnabled(true);
                    break;
            }
        }
    };




    private void initHttpSendMessage(String phone) {
        RequestParams params = new RequestParams(Configution.HOST + Configution.SENDMESSAGE);
        params.addBodyParameter("telephone", phone);
        params.addBodyParameter("type", "4");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResponsDataBean responsDataBean = JSON.parseObject(result, ResponsDataBean.class);
                    if (responsDataBean.getCode().equals("1000")){
                        showCounter();
                    }
                    ToastUtils.show(getApplicationContext(), responsDataBean.getMsg(), 100);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.show(getApplicationContext(), "网络连接失败",100);
                tvGetcode.setEnabled(true);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


}
